package com.ellecity06.cwhiskymall.ui.search.result

import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import androidx.core.widget.addTextChangedListener
import androidx.fragment.app.FragmentTransaction
import androidx.lifecycle.lifecycleScope
import com.ellecity06.common.base.BaseMvvmActivity
import com.ellecity06.common.ktx.observeEvent
import com.ellecity06.common.ktx.statusBar
import com.ellecity06.cwhiskymall.R
import com.ellecity06.cwhiskymall.databinding.ActivitySearchResultBinding
import com.ellecity06.cwhiskymall.ui.search.SearchIntent
import com.ellecity06.cwhiskymall.ui.search.SearchState
import com.ellecity06.cwhiskymall.ui.search.SearchViewModel
import com.ellecity06.cwhiskymall.ui.search.history.SearchHistoryFragment

/**
 * @author ellecity06
 * @time 2024/11/2 9:35
 * @des
 */
class SearchResultActivity :
    BaseMvvmActivity<ActivitySearchResultBinding, SearchViewModel>(), View.OnClickListener {
    private val keyword: String by lazy { intent.getStringExtra("keyword") ?: "" }

    private val historyFragment: SearchHistoryFragment by lazy { SearchHistoryFragment.newInstance() }
    private val resultFragment: SearchResultFragment by lazy {
        SearchResultFragment.newInstance(
            keyword
        )
    }

    override val userBaseTitle: Boolean
        get() = false

    override fun inflateBinding(): ActivitySearchResultBinding {
        return ActivitySearchResultBinding.inflate(layoutInflater)
    }

    override fun initialize(savedInstanceState: Bundle?) {
        statusBar(binding.statusBar)
        initView()
        lifecycleScope.launchWhenCreated {
            viewModel.intentChannel.send(
                SearchIntent.Search(
                    keyword
                )
            )
        }
    }

    override fun initObserver() {
        viewModel.state.observeEvent(this) {
            when (it) {
                is SearchState.ShowResultFragment -> {
                    try {
                        binding.etSearch.setText(it.keyword)
                        binding.etSearch.setSelection(it.keyword.length)
                    } catch (e: Exception) {

                    }
                    showResult()
                }
                else -> {}
            }
        }
    }

    override fun initEvent() {
        binding.tvSearch.setOnClickListener(this)
        binding.ivBack.setOnClickListener(this)
        binding.etSearch.setOnKeyListener { v, keyCode, event ->
            if (keyCode == KeyEvent.KEYCODE_ENTER && event?.action == KeyEvent.ACTION_UP) {
                val copy = binding.etSearch.text.toString().trim()
                search(copy)

            }
            false
        }
        binding.etSearch.addTextChangedListener {
            val text = binding.etSearch.text.toString().trim()
            if (text.isEmpty()) {
                showHistory()
            }
        }
    }

    private fun initView() {
        binding.etSearch.setText(keyword)
//        showResult()

    }

    /**
     * 显示历史搜索
     */
    private fun showHistory() {
        val ft: FragmentTransaction = supportFragmentManager.beginTransaction()
        if (resultFragment.isAdded) ft.hide(resultFragment)
        if (historyFragment.isAdded) {
            historyFragment.fetchData()
            ft.show(historyFragment).commitAllowingStateLoss()
        } else {
            ft.add(R.id.fl_fragment_container, historyFragment, "history_fragment")
                .commitAllowingStateLoss()
        }


    }

    /**
     * 显示搜索结果
     */
    private fun showResult() {
        val ft: FragmentTransaction = supportFragmentManager.beginTransaction()
        if (historyFragment.isAdded) ft.hide(historyFragment)
        if (resultFragment.isAdded) {
            ft.show(resultFragment).commitAllowingStateLoss()
        } else {
            ft.add(R.id.fl_fragment_container, resultFragment, "result_fragment")
                .commitAllowingStateLoss()
        }


//        ft.commitAllowingStateLoss()
    }

    private fun search(keyword: String) {
        lifecycleScope.launchWhenCreated {
            viewModel.intentChannel.send(
                SearchIntent.AddHistory(
                    keyword
                )
            )
            viewModel.intentChannel.send(
                SearchIntent.Search(
                    keyword
                )
            )

        }
    }

    private fun fetchHistory() {
        lifecycleScope.launchWhenCreated {
            viewModel.intentChannel.send(SearchIntent.FetchHistory)
        }
    }

    override fun onClick(view: View?) {
        when (view?.id) {
            binding.tvSearch.id -> {
                val keyword = binding.etSearch.text.toString().trim()
                search(keyword)
            }
            binding.ivBack.id -> {
                onBackPressed()
            }
        }
    }

}